const { createClient } = require("redis")
const process = require('process')

const counter_key = 'short_url:id_counter'
const urlhash_key = 'short_url:hash_key'

async function shorten(client, url) {
    const seqnum = await client.incr(counter_key)
    const shortid = base36(seqnum)
    await client.hSet(urlhash_key, shortid, url)
}

function base36(num) {
    const alphabets = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let result = ''
    while (num != 0) {
        remainder = num % 36;
        result += alphabets[remainder];
        num = Math.floor(num / 36);
    }
    return result.length === 0 ? alphabets[0] : result
}

async function restore(client, shortid) {
    return await client.hGet(urlhash_key, shortid)
}

async function run() {
    const client = createClient({
        url: 'redis://localhost:6379'
    })
    client.on('error', (err) => console.log('Redis Client Error', err));
    await client.connect();
    await client.incrBy(counter_key, 100000)
    const urls = [
        'https://github.com/redis/node-redis',
        'https://devdocs.io/python~3.8/library/math#math.modf',
        'https://weread.qq.com/web/reader/75732070719551157574079k6c8328f022d6c8349cc72d5'
    ];
    for (let url of urls) {
        await shorten(client, url)
    }

    let keys = await client.hKeys(urlhash_key)
    for (let k of keys) {
        console.log(k)
        let originurl = await restore(client, k)
        console.log(originurl)
    }
    process.exit(0)
}

run().catch(err => console.log(err))